package com.ruoyi.storage.service.impl;

import java.util.List;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.storage.domain.*;
import com.ruoyi.storage.mapper.*;
import com.ruoyi.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.storage.service.IProcessingRecordService;

/**
 * 加工单管理Service业务层处理
 * 
 * @author 庞一恺
 * @date 2025-01-11
 */
@Service
public class ProcessingRecordServiceImpl implements IProcessingRecordService 
{
    @Autowired
    private ProcessingRecordMapper processingRecordMapper;
    @Autowired
    private WarehouseInfoMapper warehouseInfoMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private ExitRecordMapper exitRecordMapper;
    @Autowired
    private ExitDetailMapper exitDetailMapper;
    @Autowired
    private ItemDetailMapper itemDetailMapper;
    @Autowired
    private WarehouseInventoryMapper warehouseInventoryMapper;
    @Autowired
    private EntryRecordMapper entryRecordMapper;


    /**
     * 查询加工单管理
     * 
     * @param processId 加工单管理主键
     * @return 加工单管理
     */
    @Override
    public ProcessingRecord selectProcessingRecordByProcessId(Long processId)
    {
        return processingRecordMapper.selectProcessingRecordByProcessId(processId);
    }

    /**
     * 查询加工单管理列表
     * 
     * @param processingRecord 加工单管理
     * @return 加工单管理
     */
    @Override
    public List<ProcessingRecord> selectProcessingRecordList(ProcessingRecord processingRecord)
    {
        Integer warehouseId = warehouseInfoMapper.getWarehouseIdByPrincipal(Math.toIntExact(processingRecord.getWarehouseId()));
        System.out.println(warehouseId);
        if (warehouseId == null) return new ArrayList<ProcessingRecord>();
        processingRecord.setWarehouseId(Long.valueOf(warehouseId));
        return processingRecordMapper.selectProcessingRecordList(processingRecord);
    }

    /**
     * 新增加工单管理
     * 
     * @param processingRecord 加工单管理
     * @return 结果
     */
    @Transactional
    @Override
    public int insertProcessingRecord(ProcessingRecord processingRecord)
    {
        System.out.println(processingRecord.toString());
        processingRecord.setGeneratedBy(sysUserMapper.selectUserById(processingRecord.getWarehouseId()).getNickName());
        processingRecord.setWarehouseId(Long.valueOf(warehouseInfoMapper.getWarehouseIdByPrincipal(Math.toIntExact(processingRecord.getWarehouseId()))));
        processingRecord.setStartTime(DateUtils.getNowDate());// 设置开始时间为当前时间
        processingRecord.setProcessState("加工中");

        String batchId = itemDetailMapper.selectItemDetailByItemId(processingRecord.getMaterialList().get(0)) .getBatchId();
        processingRecord.setOrigin(warehouseInventoryMapper.selectWarehouseInventoryByBatchId(batchId).getOrigin());



        int rows = processingRecordMapper.insertProcessingRecord(processingRecord); //存加工单
        insertProcessingDetail(processingRecord);

        // TODO 货品同步出库，生成出库单
        //出库单部分
        ExitRecord exitRecord = new ExitRecord();
        exitRecord.setExitDetailList(new ArrayList<>());
        exitRecord.setWarehouseId(Math.toIntExact(processingRecord.getWarehouseId()));
        exitRecord.setEvidenceRecordId(String.valueOf(processingRecord.getProcessId()));
        exitRecord.setOutcomeType("加工出库");
        exitRecord.setOutcomeState("送往加工");
        exitRecord.setOutcomeDate(DateUtils.getNowDate());
        exitRecord.setGeneratedBy(processingRecord.getGeneratedBy());

        //出库详情部分
        //TODO 修改了出库详情结构

        Long totalWeight = 0L;
        int totalNum = 0;

        for (String material : processingRecord.getMaterialList()){
            ExitDetail exitDetail = new ExitDetail();
            exitDetail.setExitRecordId(Math.toIntExact(processingRecord.getProcessId()));
            //exitDetail.setItemId(material);改动

            ItemDetail itemDetail = itemDetailMapper.selectItemDetailByItemId(material);
            if (itemDetail == null) {
                System.out.println("找不到物品");
                return -1;
            }
            totalWeight += itemDetail.getWeight();
            totalNum += 1;
            exitDetail.setBatchId(itemDetail.getBatchId());

            WarehouseInventory warehouseInventory = warehouseInventoryMapper.selectWarehouseInventoryByBatchId(itemDetail.getBatchId());
            if (warehouseInventory == null) {
                System.out.println("找不到库存记录");
                return -1;
            }
            exitDetail.setOrigin(warehouseInventory.getOrigin());
            exitDetail.setGoodSpecification(warehouseInventory.getGoodSpecification());
            exitDetail.setMerchandiseKind(warehouseInventory.getRawProductId());
            exitDetail.setManufactureDate(exitRecord.getOutcomeDate());

            exitDetail.setWarehouseId(itemDetail.getWarehouseId());
            exitDetail.setAreaId(itemDetail.getAreaId());
            //exitDetail.setLocation(itemDetail.getLocation());改动
            exitDetail.setExitType("加工出库");
            exitDetail.setOrderNo(String.valueOf(processingRecord.getProcessId()));

            //exitDetailMapper.insertExitDetail(exitDetail);

            exitRecord.getExitDetailList().add(exitDetail);


        }

        exitRecord.setWeight(totalWeight);
        exitRecord.setWeightUnit("千克");
        exitRecord.setState("送往加工");
        exitRecord.setCreatedTime(DateUtils.getNowDate());
        exitRecord.setTransportQuantity(Long.valueOf(totalNum));
        exitRecord.setOrigin(String.valueOf(exitRecord.getWarehouseId()));
        exitRecordMapper.insertExitRecord(exitRecord);  //存出库单



        //删库存
        for (String material : processingRecord.getMaterialList()){
            itemDetailMapper.deleteItemDetailByItemId(material);
        }

        return rows;
    }

    /**
     * 完善加工信息
     * 
     * @param processingRecord 加工单管理
     * @return 结果
     */
    @Transactional
    @Override
    public int updateProcessingRecord(ProcessingRecord processingRecord)
    {
        processingRecord.setProcessState("已完成");
        processingRecord.setEndTime(DateUtils.getNowDate());
        int i =1;
        for (ProcessingDetail processingDetail :processingRecord.getProcessingDetailList()){
            processingDetail.setProductState("待分配");

            //TODO 待完善批次号生成
            processingDetail.setProcessedProductId(processingRecord.getMaterialId()+"PCS"+DateUtils.dateTime()+String.format("%03d", i));
            i++;

            //生成待入库库存信息
            WarehouseInventory warehouseInventory = new WarehouseInventory();
            warehouseInventory.setWarehouseId(Math.toIntExact(processingRecord.getWarehouseId()));
            warehouseInventory.setInventoryType("待入库");
            warehouseInventory.setZoneId(999999);
            warehouseInventory.setInventoryName(processingDetail.getInventoryName());
            warehouseInventory.setGoodSpecification(processingDetail.getGoodSpecification());
            warehouseInventory.setOrigin(processingDetail.getOrigin());
            warehouseInventory.setInventoryNum(Long.valueOf(processingDetail.getInventoryNum()));
            warehouseInventory.setRawProductId(processingDetail.getRawProductId());

            //TODO 批次号生成待完善
            warehouseInventory.setBatchId(processingDetail.getProcessedProductId());

            warehouseInventoryMapper.insertWarehouseInventory(warehouseInventory);

            //按数量生成单件物品详情（有编码）
            List<ItemDetail> itemDetailList = new ArrayList<>();
            for (int j = 0; j < Integer.parseInt(processingDetail.getInventoryNum()); j++) {
                ItemDetail itemDetail = new ItemDetail();
                itemDetail.setItemId(processingDetail.getProcessedProductId()+"PCS"+j); //  单件编码生成
                itemDetail.setBatchId(processingDetail.getProcessedProductId());
                itemDetail.setWarehouseId(Math.toIntExact(processingRecord.getWarehouseId()));
                itemDetail.setWeight(500L);

                itemDetailList.add(itemDetail);
            }
            if (itemDetailList.size() > 0)
            {
                itemDetailMapper.batchItemDetail(itemDetailList);
            }
        }
        processingRecordMapper.deleteProcessingDetailByProcessId(processingRecord.getProcessId());
        insertProcessingDetail(processingRecord);

        return processingRecordMapper.updateProcessingRecord(processingRecord);
    }

    /**
     * 批量删除加工单管理
     * 
     * @param processIds 需要删除的加工单管理主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteProcessingRecordByProcessIds(Long[] processIds)
    {
        processingRecordMapper.deleteProcessingDetailByProcessIds(processIds);
        return processingRecordMapper.deleteProcessingRecordByProcessIds(processIds);
    }

    /**
     * 删除加工单管理信息
     * 
     * @param processId 加工单管理主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteProcessingRecordByProcessId(Long processId)
    {
        processingRecordMapper.deleteProcessingDetailByProcessId(processId);
        return processingRecordMapper.deleteProcessingRecordByProcessId(processId);
    }

    @Override
    public int updateEntryDetail(List<ItemDetail> itemDetailList) {
        ItemDetail itemDetail0 = itemDetailMapper.selectItemDetailByItemId(itemDetailList.get(0).getItemId());
        WarehouseInventory warehouseInventory = warehouseInventoryMapper.selectWarehouseInventoryByBatchId(itemDetail0.getBatchId());
        warehouseInventory.setInventoryType("商品");
        warehouseInventory.setZoneId(itemDetail0.getAreaId());

        //生成入库单
        EntryRecord entryRecord = new EntryRecord();
        entryRecord.setEntryType("加工入库");
        entryRecord.setEntryDate(DateUtils.getNowDate());
        entryRecord.setGeneratedBy(String.valueOf(SecurityUtils.getUserId()));
        entryRecord.setWarehouseId(warehouseInventory.getWarehouseId());
        entryRecord.setEntryState("已入库");

        for (ItemDetail itemDetail : itemDetailList){
            itemDetailMapper.updateItemDetail(itemDetail);
        }

        warehouseInventoryMapper.updateWarehouseInventory(warehouseInventory);
        entryRecordMapper.insertEntryRecord(entryRecord);

        return 1;
    }

    /**
     * 新增加工详情信息
     * 
     * @param processingRecord 加工单管理对象
     */
    public void insertProcessingDetail(ProcessingRecord processingRecord)
    {
        List<ProcessingDetail> processingDetailList = processingRecord.getProcessingDetailList();
        Long processId = processingRecord.getProcessId();
        if (StringUtils.isNotNull(processingDetailList))
        {
            List<ProcessingDetail> list = new ArrayList<ProcessingDetail>();

            int i = 1;
            for (ProcessingDetail processingDetail : processingDetailList)
            {
                processingDetail.setProcessId(processId);
                processingDetail.setOrigin(warehouseInfoMapper.selectWarehouseInfoByWarehouseId(Math.toIntExact(processingRecord.getWarehouseId())).getWarehouseName());

                //TODO 生成批次号待完善
                processingDetail.setProcessedProductId(processingRecord.getMaterialId()+"PCS"+DateUtils.dateTime()+String.format("%03d", i));

                list.add(processingDetail);
                i++;
            }
            if (list.size() > 0)
            {
                processingRecordMapper.batchProcessingDetail(list);
            }
        }
    }
}
